<script setup>
import { ref, onMounted, watch, defineEmits } from "vue";
import { showToast } from "vant";
// 选择年份
const startDate = ref(["2023", "01", "01"]);
const endDate = ref(["2023", "01", "28"]);
const curDayTime = ref(new Date().getDate());
const chooseTime = ref([]);
const showPicBox = ref(false); //自定义时间弹窗
const dateIndex = ref(0);
const minDate = new Date(1990, 1, 1);
const maxDate = new Date(2050, 12, 30);
const emit = defineEmits(["changeTime"]);
// 日期确定
const onConfirm = () => {
  emit("changeTime", [beginTime.value, endTime.value]);
  showPicBox.value = false;
};
// 日期取消
const onCancel = () => {
  showPicBox.value = false;
};
const show = ref(false);
const beginTime = ref(""); //自定义时间-开始时间
const endTime = ref(""); //自定义时间-结束时间
//获取当前时间
const getData = (val) => {
  switch (val.toString()) {
    // 按日（默认当日）
    case "0":
      dateIndex.value = 0;
      chooseTime.value = [];
      curDayTime.value = new Date().getDate(); //回显当前日
      let year = new Date().getFullYear();
      let month = new Date().getMonth() + 1;
      let BigMonth = [1, 3, 5, 7, 8, 10, 12]; //大月 31天
      let allDay;
      if (BigMonth.includes(month)) {
        allDay = 31;
      } else {
        if (month == 2) {
          if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
            allDay = 29;
          } else {
            allDay = 28;
          }
        } else {
          allDay = 30;
        }
      }
      for (let i = 1; i <= allDay; i++) {
        chooseTime.value.push({ text: i, value: i });
      }
      break;
    case "1":
      dateIndex.value = 1;
      chooseTime.value = [];
      curDayTime.value = new Date().getMonth() + 1; //回显当前月
      for (let i = 1; i <= 12; i++) {
        chooseTime.value.push({ text: i, value: i });
      }
      break;
    case "2":
      chooseTime.value = [];
      dateIndex.value = 2;
      curDayTime.value = new Date().getFullYear(); //回显当前年
      for (
        let i = new Date().getFullYear() - 5;
        i <= new Date().getFullYear();
        i++
      ) {
        chooseTime.value.push({ text: i, value: i });
      }
      break;
    case "3":
      dateIndex.value = 3;
      beginTime.value = new Date(
        new Date().getTime() - 365 * 24 * 60 * 60 * 1000
      ).format("yyyy-MM-dd");
      endTime.value = new Date(
        new Date().getTime() - 365 * 24 * 60 * 60 * 1000
      ).format("yyyy-MM-dd");
      showPicBox.value = true;
      chooseTime.value = [];
      break;
    default:
      break;
  }
};
defineExpose({ getData });
function YMD_daxiao(str1, str2) {
  // 方法一:将年月日转化为数字
  let arr1 = str1.split("-");
  let arr2 = str2.split("-");
  str1 = Number(arr1.join(""));
  str2 = Number(arr2.join(""));
  // 小于0则str1时间小，大于0则str1时间大
  return str1 - str2;
}
const getTime = (picker) => {
  if (whichPicker.value == 0) {
    beginTime.value = `${picker.selectedValues[0]}-${picker.selectedValues[1]}-${picker.selectedValues[2]}`;
  } else {
    endTime.value = `${picker.selectedValues[0]}-${picker.selectedValues[1]}-${picker.selectedValues[2]}`;
  }
  if (beginTime && endTime) {
    if (YMD_daxiao(beginTime.value, endTime.value) > 0) {
      showToast("起始时间不能大于结束时间");
    }
  }
};
const whichPicker = ref(0);
const getTimePiker = (val) => {
  switch (val) {
    case 0:
      whichPicker.value = 0;
      break;
    case 1:
      whichPicker.value = 1;
      break;
  }
};
watch(
  () => [curDayTime.value, dateIndex.value],
  (newVal) => {
    if (newVal[1] != 3) {
      emit("changeTime", newVal);
    }
    console.log(newVal), { deep: true, immediate: true };
  }
);
onMounted(() => {
  getData(0);
});
</script>

<template>
  <div class="datePicker">
    <div class="datePicLeft" style="margin-right: 8px">
      <div
        class="day"
        :class="dateIndex == 0 ? 'active' : ''"
        style="border-radius: 4px 0 0 4px"
        @click="getData(0)"
      >
        按日
      </div>
      <div
        class="month"
        :class="dateIndex == 1 ? 'active' : ''"
        @click="getData(1)"
      >
        按月
      </div>
      <div
        class="year"
        :class="dateIndex == 2 ? 'active' : ''"
        @click="getData(2)"
      >
        按年
      </div>
      <div
        class="customize"
        :class="dateIndex == 3 ? 'active' : ''"
        @click="getData(3)"
        style="
          border-right: 1px solid rgba(38, 111, 232, 0.7);
          border-radius: 0 4px 4px 0;
        "
      >
        自定义
      </div>
    </div>
    <div class="datePicRight">
      <!-- 下拉框 -->
      <van-dropdown-menu>
        <van-dropdown-item v-model="curDayTime" :options="chooseTime" />
      </van-dropdown-menu>
    </div>
    <!-- 日期选择 -->
    <van-popup
      v-model:show="showPicBox"
      :style="{ height: '55%', width: '100%' }"
    >
      <div class="topBox">
        <div class="left" @click="onCancel">取消</div>
        <div class="center">选择时间</div>
        <div class="right" @click="onConfirm">确定</div>
      </div>
      <van-date-picker
        v-model="startDate"
        :min-date="minDate"
        :max-date="maxDate"
        @change="getTime"
      >
        <template #toolbar>
          <div class="timePick">
            <div
              class="left"
              @click="getTimePiker(0)"
              :class="whichPicker == 0 ? 'active' : ''"
            >
              <input
                class="inputTime"
                type="text"
                readonly="readonly"
                v-model="beginTime"
                name=""
                id=""
                placeholder="开始时间"
              />
            </div>
            <div style="padding: 0 9px">至</div>
            <div
              class="right"
              @click="getTimePiker(1)"
              :class="whichPicker == 1 ? 'active' : ''"
            >
              <input
                class="inputTime"
                type="text"
                readonly="readonly"
                v-model="endTime"
                name=""
                id=""
                placeholder="结束时间"
              />
            </div>
          </div>
        </template>
      </van-date-picker>
    </van-popup>
  </div>
</template>

<style lang="scss" scoped>
.datePicker {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
  margin-top: 12px;
  .datePicLeft {
    display: flex;
    border-radius: 4px 4px 4px 4px;
    opacity: 1;
    .day,
    .month,
    .year,
    .customize {
      border-left: 1px solid rgba(38, 111, 232, 0.7);
      border-top: 1px solid rgba(38, 111, 232, 0.7);
      border-bottom: 1px solid rgba(38, 111, 232, 0.7);
      padding: 7px 10px;
      font-size: 14px;
      font-family: PingFang SC-Medium, PingFang SC;
      font-weight: 500;
      color: #266fe8;
    }
    .active {
      font-size: 14px;
      font-family: PingFang SC-Medium, PingFang SC;
      font-weight: 500;
      color: #ffffff;
      background-color: #266fe8;
    }
  }
  .datePicRight {
    flex: 1;
    :deep(.van-dropdown-menu__title) {
      width: 100%;
      height: 36px;
      line-height: 36px;
    }
    :deep(.van-cell__value) {
      padding-right: 5%;
    }
    :deep(.van-dropdown-menu) {
      height: 36px;
    }
    ::v-deep .van-dropdown-menu__bar {
      height: 36px;
    }
    ::v-deep .van-dropdown-menu__item {
      justify-content: start;
      background: #f5f5f5;
    }
    ::v-deep .van-dropdown-menu__title:after {
      position: absolute;
      top: 50%;
      right: 5%;
      margin-top: -10px;
      border: 3px solid;
      border-color: transparent transparent #266fe8 #266fe8;
      transform: rotate(-45deg);
      opacity: 0.8;
      content: "";
      width: 6px;
      height: 6px;
      margin-right: 10px;
    }
  }
  .topBox {
    display: flex;
    padding: 16px;
    align-items: center;
    .left,
    .right {
      color: rgba(0, 0, 0, 0.4);
      font-size: 16px;
      width: 20%;
      text-align: center;
    }
    .center {
      font-size: 20px;
      font-weight: 500;
      flex: 1;
      text-align: center;
    }
    .right {
      color: #266fe8;
    }
  }
  .timePick {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 16px;
    .left,
    .right {
      width: 137px;
      height: 34px;
      border-radius: 4px 4px 4px 4px;
      border: 1px solid transparent;
      .inputTime {
        height: 100%;
        width: 100%;
        border: none;
        outline: none;
        border: none;
        -webkit-appearance: none; //隐藏移动端小箭头
        border-radius: 4px 4px 4px 4px;
        color: rgba(0, 0, 0, 0.4);
        background: rgba(0, 0, 0, 0.04);
        font-size: 14px;
        text-indent: 14px;
      }
      .inputTime::-webkit-input-placeholder {
        /* WebKit, Blink, Edge */
        font-size: 14px;
        color: rgba(0, 0, 0, 0.4);
      }
      :-moz-placeholder {
        /* Mozilla Firefox 4 to 18 */
        font-size: 14px;
        color: rgba(0, 0, 0, 0.4);
      }
      .inputTime::-moz-placeholder {
        /* Mozilla Firefox 19+ */
        font-size: 14px;
        color: rgba(0, 0, 0, 0.4);
      }

      :-ms-input-placeholder {
        /* Internet Explorer 10-11 */
        font-size: 14px;
        color: rgba(0, 0, 0, 0.4);
      }
      .inputTime::-ms-input-placeholder {
        /* Microsoft Edge */
        font-size: 14px;
        color: rgba(0, 0, 0, 0.4);
      }
    }
    .active {
      border: 1px solid #266fe8;
    }
  }
}
</style>